// 基础URL配置
const BASE_URL = 'https://192.168.1.2:8080'

// 请求方法封装
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 显示加载提示
    wx.showLoading({
      title: '加载中...',
      mask: true
    })

    // 获取token
    const token = wx.getStorageSync('token')
    
    // 构建请求配置
    const requestConfig = {
      url: `${BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'content-type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        ...options.header
      },
      success: (res) => {
        wx.hideLoading()
        // 处理响应
        if (res.statusCode === 200 && res.data.status === 200) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // token过期处理
          wx.removeStorageSync('token')
          wx.navigateTo({
            url: '/pages/login/login'
          })
          reject(new Error('登录已过期'))
        } else {
          wx.showToast({
            title: res.data.msg || '请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    }

    // 执行请求
    wx.request(requestConfig)
  })
}

// 封装常用的请求方法
const http = {
  get: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'GET',
      ...options
    })
  },

  post: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'POST',
      ...options
    })
  },

  put: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'PUT',
      ...options
    })
  },

  delete: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'DELETE',
      ...options
    })
  }
}

// 请求拦截器
const interceptor = {
  request: (config) => {
    // 可以在这里添加token等认证信息
    const token = wx.getStorageSync('token')
    if (token) {
      config.header = {
        ...config.header,
        'Authorization': `Bearer ${token}`
      }
    }
    return config
  },
  response: (response) => {
    // 可以在这里统一处理响应
    return response
  }
}

// 导出
module.exports = http